package com.powernode.common.feign;

import com.powernode.common.result.Result;
import com.powernode.common.result.ResultCodeEnum;
import feign.FeignException;
import feign.Response;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 自定义feign decoder
 * 在feign调用结束之后统一处理事情
 */
public class FeignCustomDataDecoder implements Decoder {

    private SpringDecoder decoder;


    public FeignCustomDataDecoder(SpringDecoder decoder) {
        this.decoder = decoder;
    }


    /**
     * 在feign调用之后处理事情
     * @param response
     * @param type
     * @return
     * @throws IOException
     * @throws DecodeException
     * @throws FeignException
     */
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {

        // feign调用下游服务的返回结果
        Object object = this.decoder.decode(response, type);

        if (object == null) {
            throw new DecodeException(ResultCodeEnum.FEIGN_FAIL.getCode(), ResultCodeEnum.FEIGN_FAIL.getMessage(), response.request());
        }

        if (object instanceof Result<?>) {
            //若程序进来则说明feign执行的是业务逻辑
            //判断状态码
            Result<?> result = (Result<?>) object;

            //判断状态码 是否不等于200
            if (result.getCode().intValue() != ResultCodeEnum.SUCCESS.getCode().intValue()){
                throw new DecodeException(ResultCodeEnum.FEIGN_FAIL.getCode(), ResultCodeEnum.FEIGN_FAIL.getMessage(), response.request());
            }
        }

        return object;
    }
}
